package com.flyxiaozhu.erp.admin.controllers;

import com.flyxiaozhu.erp.core.entities.App;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.libs.SearchSpecification;
import com.flyxiaozhu.erp.core.repositories.AppRepository;
import com.flyxiaozhu.erp.core.utils.BeanUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.annotation.Secured;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Validated
public class AppController {
    @Autowired
    AppRepository appRepository;

    @Secured("ROLE_APP_SELECT")
    @RequestMapping("/app/select")
    public JSONResult getList(HttpServletRequest request, @PageableDefault Pageable pageable) {
        Page<App> page = appRepository.findAll(new SearchSpecification<>(request), pageable);

        return new JSONResult(page, pageable.getPageNumber());
    }

    @Secured("ROLE_APP_UPDATE")
    @RequestMapping("/app/update")
    public JSONResult update(App app, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new JSONResult(bindingResult);
        }

        App old = appRepository.findById(app.getId()).orElse(null);
        if (old == null) {
            return new JSONResult(ErrorCode.NO_DATA, "应用ID错误");
        }
        BeanUtils.copyProperties(app, old);
        appRepository.save(old);

        return new JSONResult().put("count", 1).put("model", old);
    }

    @Secured("ROLE_APP_INSERT")
    @RequestMapping("/app/insert")
    public JSONResult add(App app, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new JSONResult(bindingResult);
        }

        String key;
        do {
            key = RandomStringUtils.randomAlphanumeric(16);
        } while (appRepository.exitsByKey(key) > 0);

        app.setKey(key);
        app.setSecret(RandomStringUtils.randomAlphanumeric(32));
        appRepository.save(app);
        return new JSONResult().put("model", app);
    }
}
